package com.example.babydatacollector;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

import com.example.babydatacollector.EventContract.Event;

public class ChartActivity extends Activity {
	WebView webView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_chart);
		setContent();
		// Show the Up button in the action bar.
		setupActionBar();
	}

	/**
	 * Set up the {@link android.app.ActionBar}, if the API is available.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.chart, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@SuppressLint("SetJavaScriptEnabled")
	private void setContent() {
		webView = (WebView) findViewById(R.id.chart);
		webView.setWebChromeClient(new WebChromeClient());
		webView.getSettings().setJavaScriptEnabled(true);
		webView.addJavascriptInterface(new JavaScriptInterface(this),
				"jsInterface");
		// webView.loadUrl("http://chart.apis.google.com/chart?cht=p3&chs=500x200&chd=e%3aTNTNTNGa&chts=000000,16&chtt=A%20Better%20Web&chl=Hello|Hi|anas|Explorer&chco=FF5533,237745,9011D3,335423&chdl=Apple|Mozilla|Google|Microsoft");
		webView.loadUrl("file:///android_asset/chart.html");
	}

	public class JavaScriptInterface {
		Context mContext;

		/** Instantiate the interface and set the context */
		JavaScriptInterface(Context c) {
			mContext = c;
		}

		@JavascriptInterface
		public void draw() {
			buildRows();

			webView.loadUrl("javascript:drawChart()");
		}

		private void buildRows() {
			EventDbHelper mDbHelper = new EventDbHelper(mContext);
			SQLiteDatabase db = mDbHelper.getReadableDatabase();

			String types[] = { MainActivity.TYPE_EAT, MainActivity.TYPE_SLEEP,
					MainActivity.TYPE_PISS, MainActivity.TYPE_SHIT };
			for (String type : types) {
				addRowsFromDB(db, type);
			}
		}

		private void addRowsFromDB(SQLiteDatabase db, String type) {
			String[] projection = { Event.COLUMN_NAME_START_TIME,
					Event.COLUMN_NAME_END_TIME };
			String sortOrder = Event.COLUMN_NAME_START_TIME + " ASC";
			String selection = Event.COLUMN_NAME_TYPE + "=?";
			String[] selectionArgs = { type };

			Cursor cursor = db.query(Event.TABLE_NAME, // The table to query
					projection, // The columns to return
					selection, // The columns for the WHERE clause
					selectionArgs, // The values for the WHERE clause
					null, // don't group the rows
					null, // don't filter by row groups
					sortOrder // The sort order
					);

			int count = 1;
			if (cursor.moveToFirst()) {
				do {
					long startTime = cursor
							.getLong(cursor
									.getColumnIndexOrThrow(Event.COLUMN_NAME_START_TIME));
					int endTimeColumnIndex = cursor
							.getColumnIndexOrThrow(Event.COLUMN_NAME_END_TIME);
					long endTime;
					if (cursor.isNull(endTimeColumnIndex)) {
						endTime = startTime;
					} else {
						endTime = cursor.getLong(endTimeColumnIndex);
					}

					webView.loadUrl(String.format(
							"javascript:addRow('%s', '%s', %d, %d)", type, type
									+ " - " + count, startTime, endTime));

					count++;
				} while (cursor.moveToNext());
			}
		}
	}
}
